package org.study.mybatis.result;


import java.lang.reflect.Constructor;
import java.util.*;

/**
 * 通过mapperMethod解析的type类型，创建对应的对象
 */
public class DefaultObject {
    public static Object createObjectByType(Class clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException {
        Class classToCreate;
        //是数组类型
        if (clazz == List.class || clazz == Collection.class || clazz == Iterable.class) {
            classToCreate = ArrayList.class;
        }
        //map类型
        else if (clazz == Map.class) {
            classToCreate = HashMap.class;
        }
        //set类型
        else if (clazz == Set.class) {
            classToCreate = HashSet.class;
        } else {
            //都不是，那就是自定义类型，主要用这个
            classToCreate = clazz;
        }
        Constructor constructor = classToCreate.getDeclaredConstructor();
        //查看是否有权限
        if (!constructor.isAccessible()) {
            //没有就设置成为有权限
            constructor.setAccessible(true);
        }
        //生成对象
        Object obj = clazz.newInstance();
        return obj;
    }
}
